package com.haierp.service.purchase.impl;

import java.text.ParseException;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.framework.service.impl.SuperServiceImpl;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.haierp.enums.GeneralStatus;
import com.haierp.mapper.TaskPurchaseMapper;
import com.haierp.model.purchase.Receipt;
import com.haierp.model.purchase.TaskPurchase;
import com.haierp.service.purchase.IReceiptService;
import com.haierp.service.purchase.ITaskPurchaseService;
import com.haierp.util.DateUtil;
import com.haierp.vo.TaskPurchaseVO;
@Service
public class TaskPurchaseServiceImpl extends SuperServiceImpl<TaskPurchaseMapper, TaskPurchase> implements ITaskPurchaseService {

	@Autowired
	private IReceiptService receiptService;
	
	@Override
	public List<TaskPurchase> queryTaskPurchaseBySubTask(Long subTaskId) {
		 EntityWrapper<TaskPurchase> entityWrapper = new EntityWrapper<>(); 
		 //未被关闭子任务的采购任务流水
		entityWrapper.where("sub_task_id={0} and status != {1}", subTaskId,GeneralStatus.CLOSE.getCode());
		return baseMapper.selectList(entityWrapper);
	}
	
	
	@Override
	public List<TaskPurchase> queryTaskPurchaseList(Long buyerId,Integer status) {
//		 EntityWrapper<TaskPurchase> entityWrapper = new EntityWrapper<>(); 
		 //该子任务没有被关闭的采购任务流水
		 String todayStr =  DateUtil.formatDate(new Date(), DateUtil.SIMPLE_DATE_PARTEN);
		 Date dateBegin = null;
		 Date dateEnd = null;
		 try {
			 dateBegin = DateUtil.convertStr2Date(todayStr,DateUtil.SIMPLE_DATE_PARTEN);
			 dateEnd = DateUtil.convertStr2Date(todayStr+" 23:59:59",DateUtil.DATE_PARTEN);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		 TaskPurchaseVO tpVO = new TaskPurchaseVO();
		 tpVO.setBuyerId(buyerId);
		 tpVO.setStatus(status);
		 tpVO.setStartTime(dateBegin);
		 tpVO.setEndTime(dateEnd);
//		entityWrapper.where("buyer_id={0} and status = {1} and gmt_create>{2} and gmt_create<{3}", buyerId,status,dateBegin,dateEnd);
//		 entityWrapper.where("buyer_id={0} and status = {1}", buyerId,status);
		return baseMapper.queryTaskPurchaseList(tpVO);
	}


	@Override
	public void createReceipt(Receipt receipt, List<TaskPurchase> tps) {
		if(receipt!=null){
			receiptService.insert(receipt);
			tps.forEach(tp->{
				tp.setStatus(GeneralStatus.CLOSE.getCode());
				tp.setReceiptId(receipt.getId());
				tp.setGmtModify(new Date());
				
			});
			this.baseMapper.updateBatchById(tps);
			
		}else{
			throw new RuntimeException("没有小票");
		}
		
	}
	

}
